package top.glkj.hms.security;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import top.glkj.hms.utils.ResultFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/28 1:51
 */
@Slf4j
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {
    /**
     * 登录失败返回结果
     *
     * @param request   请求
     * @param response  响应
     * @param exception 异常
     * @author xgl
     * @date 2020/11/14
     **/
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        String str = "";

        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException) {
            log.info("【登录失败】" + exception.getMessage());
            str = JSONObject.toJSONString(ResultFactory.isException(exception.getMessage()));
        }
        if (exception instanceof LockedException) {
            log.info("【登录失败】" + exception.getMessage());
            str = JSONObject.toJSONString(ResultFactory.isException(exception.getMessage()));
        }
        if (exception instanceof BadCredentialsException) {
            log.info("【登录失败】" + exception.getMessage());
            str = JSONObject.toJSONString(ResultFactory.isException(exception.getMessage()));
        }

        if ("".equals(str)) {
            str = JSONObject.toJSONString(ResultFactory.isException(exception.getMessage()));
        }
        out.write(str.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
    }
}
